import mysql.connector
import os,sys
from datetime import datetime
from qcloud_cos import CosConfig, CosS3Client

# 配置 COS SDK
secret_id = "AKIDYy95mGWXIo69wTs3yd5KK4auzoOjpfGc"
secret_key = "81f4FBtMbbLq7AELNDznU0LSL1SecNs9"
region = "ap-hongkong"
bucket = "hcecpod-1343049753"

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)

def get_all_filepath(folder_path):
    paths = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            return_path=os.path.join(root, file).replace('\\','/')
            paths.append(return_path)
    return paths

def upload_file(local_path,cos_path):
    if os.path.isfile(local_path):
        try:
            client.upload_file(Bucket=bucket, LocalFilePath=local_path, Key=cos_path)
            return True
        except:
            return False
        
def upload_patterns():
    # 数据库连接信息（请修改为你的数据库信息）
    db_config = {
        "host": "43.161.240.94",
        "user": "hcecpod_com",
        "password": "Xcd9sMZ9DMBBkbMf",
        "database": "hcecpod_com",
    }

    dir='Z:/跨境/男装/0-2023秋季/5-短袖T/IP款图-0228/3.11-大力水手19款/新建文件夹/upload'
    paths=get_all_filepath(dir)
    conn = mysql.connector.connect(**db_config)
    mycursor = conn.cursor()
    
    now = datetime.now()
    formatted_date = now.strftime("%Y-%m-%d")
    for path in paths:
        mycursor.execute("select max(id) from data_pattern") 
        myresult = mycursor.fetchone()
        begin_id=myresult[0]+1
        file_name=os.path.basename(path)
        path=path.replace('//','/')
        name='TK_' +str(begin_id)
        pic=name+os.path.splitext(file_name)[1]
        name_original=file_name
        dict=[] 
        dict.append(name)
        dict.append(pic)
        dict.append('pattern')
        dict.append(name_original)
        dict.append(formatted_date)
        dict.append('运营上传')   
        dict.append('秋霞')
        dict.append('小成')
        dict=tuple(dict)
        print(dict)
        if(upload_file(path,'pattern/'+pic)):
            try:
                sql = "insert into data_pattern (name,pic,pic_file,pic_original,date,sort,editor,belong) values (%s,%s,%s,%s,%s,%s,%s,%s)" 
                mycursor.execute(sql,dict) 
                conn.commit()
                print('success:',path)
            except:                
                print('error:',path)
                continue
            
upload_patterns()